<?php

namespace App\Http\Common;

use Illuminate\Support\Facades\Validator;

class BaserValidate
{
    /**
     * 当前规则
     * @var array
     */
    protected $rule = [];

    /**
     * 验证的提示信息
     * @var array
     */
    protected $message = [];

    /**
     * 验证失败错误信息
     * @var array
     */
    protected $error = [];

    /**
     * 验证场景
     * @var array
     */
    protected $scene = [];

    /**
     * 当前验证场景
     * @var null
     */
    protected $currentScene = null;

    /**
     * 场景验证的规则
     * @var array
     */
    protected $sceneRule = [];

    /**
     * 设置场景验证名
     * @param $name 场景验证
     * @return $this
     */
    public function setScene($name){
        $this->currentScene = $name;
        return $this;
    }

    /**
     * 获取场景验证规则
     * @return bool
     */
    protected function getSceneRule(){
        $scene = $this->currentScene;
        if (empty($scene)) return true;

        //指定场景不存在于数组
        if (!isset($this->scene[$scene])){
            $this->error = $scene . "场景验证未找到";
            return false;
        }

        //指定场景存在于数组
        $scene = $this->scene[$scene];
        $this->sceneRule = $scene;
        return true;
    }

    /**
     * 获取错误
     * @return array
     */
    public function getError(){
        return $this->error;
    }

    /**
     * 数据验证
     * @param $data 验证数据
     * @param array $rules  验证规则
     * @param array $message 验证规则信息
     * @return bool
     */
    public function check($data, $rules = [], $message = []){
        //初始化错误数组
        $this->error = [];

        //规则数组为空
        if (empty($rules)) $rules = $this->rule;

        //验证规则提示信息为空
        if (empty($message)) $message = $this->message;

        //获取场景验证规则
        if (!$this->getSceneRule()) return false;

        //场景验证规则不为空时
        if (!empty($this->sceneRule)){
            $newRules = [];
            foreach ($this->sceneRule as $key => $value){
                if (array_key_exists($value, $rules)){
                    $newRules[$value] = $rules[$value];
                }
            }
            $rules = $newRules;
        }

        //验证
        $validator = Validator::make($data, $rules, $message);
        if ($validator->fails()){
            $this->error = $validator->errors()->first();
            return false;
        }
        return empty($this->error) ? true : false;
    }
}
